#! /usr/bin/env python
# coding: UTF-8
# python2.7
 
from Tkinter import *
import Tkinter as tk
import threading
from thread import *
import time
from socket import *
import socket
import sys

HOST = socket.gethostbyname(socket.gethostname())#'127.0.0.1'
PORT = 8808
BUFSIZ = 1024
ADDR = (HOST, PORT)
class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid()
        self.createFrameTop()
        self.createFrameMiddle()
        self.createFrameBottom()
        self.flag = False
    def createFrameTop(self):
        self.frmTop = tk.LabelFrame(root, text='Top')
        self.chatText = tk.Text(self.frmTop, height=15, width=80)     
        self.chatText.tag_config('blue', foreground='blue', font=('Tempus Sans ITC',15))
        self.chatText.tag_config('red', foreground='red', font=('Tempus Sans ITC',15))
        self.chatText.tag_config('black', foreground='black', font=('Tempus Sans ITC',15))
        self.chatScl = Scrollbar(self.frmTop)
        self.chatScl['command'] = self.chatText.yview
        self.chatText['yscrollcommand']=self.chatScl.set
        self.frmTop.grid(row = 0, column = 0, sticky = 'w'+'e'+'n'+'s')
        self.chatText.grid(row = 0, column = 0, sticky = 'w'+'e'+'n'+'s')
        self.chatScl.grid(row = 0, column = 1, sticky = 'w'+'e'+'n'+'s')
    def createFrameMiddle(self):
        self.frmMiddle = tk.LabelFrame(root, text='Middle')
        self.inputText = tk.Text(self.frmMiddle, height=8, width=80)
        self.inputText.bind("<Return>", self.sendMessage)
        self.inputScl = Scrollbar(self.frmMiddle)
        self.inputScl['command'] = self.inputText.yview
        self.inputText['yscrollcommand']=self.inputScl.set
        self.frmMiddle.grid(row = 1, column = 0, sticky = 'w'+'e'+'n'+'s')
        self.inputText.grid(row = 0, column = 0, sticky = 'w'+'e'+'n'+'s')
        self.inputScl.grid(row = 0, column = 1, sticky = 'w'+'e'+'n'+'s')
    def createFrameBottom(self):
        self.frmButton = tk.LabelFrame(root, text='Bottom')
        self.btnSend = tk.Button(self.frmButton, text='send', width=10, command=self.sendMessage)
        self.btnClose = tk.Button(self.frmButton, text='close', width=10, command=self.Close) 
        self.frmButton.grid(row = 2, column = 0, ipadx=0, ipady=0, sticky = 'w'+'e'+'n'+'s')
        self.btnSend.grid(row = 0, column = 0, padx=50, pady=0, sticky = 'e')
        self.btnClose.grid(row = 0, column = 1, padx=150, pady=0, sticky = 'e')
    def sendMessage(self, event=None):
        message = self.inputText.get('0.0', END)       
        theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
        self.chatText.insert(END, '客户端 ' + theTime +' 说： \n') 
        self.chatText.insert(END, '  ' + message + '\n', 'blue')
        self.chatText.see(END) 
        self.sendername='服务器 ' 
        if self.flag == True:
            self.send_flag_count+=1
            self.clientSock.send(message.encode('utf8')) 
        else:            
            self.chatText.insert(END, '你还未与客户端建立连接，客户端无法接受您的消息 \n', 'red')        
        self.inputText.delete(0.0, END)
#         print 'se：',self.sendername  
    def Close(self):
        sys.exit()  
    def receiveMessage(self):        
        try:
            self.clientSock = socket.socket(AF_INET, SOCK_STREAM)        #SOCK_STREAM(流套接字)和SOCK_DGRAM(数据报套接字),(套接字socket分为Unix socket和Internet socket)
            self.clientSock.connect(ADDR) 
            self.flag = True
            self.sendername='服务器 ' 
            self.send_flag_count=0
            self.chatText.insert(END, '服务器已经就绪...... \n')
            self.clientSock.send('Y')    #bytes('Y', 'utf-8')
        except:
            self.clientSock.close() 
            self.flag = False 
            self.chatText.insert(END, '您还未与服务器端建立连接，请检查服务器端是否已经启动\n', 'red') 
            return
        while True: 
            try: 
                if self.flag == True: 
                    try:
                        self.serverMsg = str(self.clientSock.recv(BUFSIZ))#.encode('utf-8')
#                     print 're1：',self.sendername
                    except:
                        pass 
                    if self.serverMsg.find(' , ')!=-1 and len(self.serverMsg.split(' , ')[-1])==5:
                        self.sendername=self.serverMsg.split(' , ')[-1]
                        self.serverMsg=' , '.join(self.serverMsg.split(' , ')[:-1])
                    if self.send_flag_count!=0:
                        self.send_flag_count-=1
#                         print 'client1-2:',self.send_flag_count
                        self.sendername='服务器 ' 
                        continue                    
#                     print self.serverMsg
                    if self.serverMsg == 'Y': 
                        self.chatText.insert(END, '客户端已经与服务器端建立连接......\n') 
                    elif self.serverMsg == 'N': 
                        self.chatText.insert(END, '服务器端与客户端连接失败......\n') 
                    elif not self.serverMsg: 
                        continue 
                    else:    
#                         print 're2：',self.sendername                    
                        theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
                        self.chatText.insert(END, self.sendername+' ' + theTime +' 说： \n') 
                        self.chatText.insert(END, '  ' + str(self.serverMsg)+'\n', 'red')
                        self.chatText.see(END)
                        self.sendername='服务器 ' 
                else: 
                    break
            except (EOFError):     #, msg
                ## raise msg 
                self.clientSock.close() 
                break 
               
    def startNewThread(self):       
        thread1 = threading.Timer(1, self.receiveMessage)
        thread1.setDaemon(True)
        thread1.start() 
 
if __name__=="__main__":
    root = tk.Tk()
    root.title("Client")
    root.resizable(False,False)
    app = Application(master=root)
    app.startNewThread()
    app.mainloop()









